package com.gaogzhen.appScenarios.sellTicket;

import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Vector;

/**
 * @author Administrator
 * @version 1.0
 * @description 售票测试
 * @date 2022-10-14 10:30
 */
@Slf4j(topic = "c.TestSellTicket")
public class TestSellTicket {
    public static void main(String[] args) throws InterruptedException {
        // 卖票窗口
        TicketWindow ticketWindow = new TicketWindow(100);
        // 售票员线程列表
        int initial = 2000;
        List<Thread>  seller = new ArrayList<>(initial);
        // 每次销售的票数列表
        List<Integer> sellTickets = new Vector<>();
        for (int i = 0; i < initial; i++) {
            Thread t = new Thread(() -> {
                int amount = ticketWindow.sell(randomAmount() );
                try {
                    Thread.sleep(randomAmount() * 100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                sellTickets.add(amount);
            }, "售票员" + i);
            seller.add(t);
            t.start();
        }
        for (Thread thread : seller) {
//            thread.start();
            thread.join();
        }

        // 通过销售票数和剩余票数检查是否有问题
        int remainders = ticketWindow.getCount();
        log.debug("余票：{}", remainders);
        int sells = sellTickets.stream().mapToInt(i -> i).sum();
        log.debug("卖出票数：{}", sells);

    }

    /**
     * Random线程安全
     */
    static Random random = new Random();

    /**
     * 随机票数1~5
     * @return  票数
     */
    public static int randomAmount() {
        return random.nextInt(5) + 1;
    }
}
